﻿#region 命名空间

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WinnerCMS.BLL.PageFactory;
using WinnerCMS.BLL.PageFactory.ManageHtml;
using WinnerCMS.Common;
using WinnerCMS.Data;
using WinnerCMS.Model;
using WinnerCMS.CacheStorager;
using System.Linq.Expressions;
using WinnerCMS.Model.Enum;

#endregion

namespace WinnerCMS.BLL
{
    public class CoreManage
    {
        private static readonly CoreDal MyDAL;

        static CoreManage()
        {
            MyDAL = new CoreDal();
        }

        /// <summary>
        /// 取得内容的基本属性
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Core GetBaseInfo(int id)
        {
            return MyDAL.GetInfo(id);
        }

        /// <summary>
        /// 取得内容的基本属性
        /// </summary>
        /// <param name="modelId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <remarks>没必要不要调用，建议调用具体表对应的GetInfo</remarks>
        public dynamic GetBaseInfo(byte modelId, int id)
        {
            switch (modelId)
            {
                case 1:
                    return new SoftDal().GetInfo(id);
                case 2:
                    return new ArticleDal().GetInfo(id);
                case 3:
                    return new PhotoDal().GetInfo(id);
                case 4:
                    return new GoodsDal().GetInfo(id);

                default:
                    throw new NotSupportedException("输入值不正确。");
            }
        }

        /// <summary>
        /// 替换内容
        /// </summary>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        /// <param name="IDs"></param>
        /// <param name="usedRegex"></param>
        /// <returns></returns>
        public Result Replace(string oldValue, string newValue, string IDs, bool usedRegex)
        {
            Result res = new Result();
            if (oldValue.Length == 0)
            {
                res.Errors = "原内容不能为空！";
                return res;
            }
            if (IDs.Length == 0)
            {
                res.Errors = "请选择文章！";
                return res;
            }
            new CoreManage().Replace(oldValue, newValue, IDs, usedRegex);

            return res;
        }

        public IList<Core> SpecialPageBindList(int specialId, PagingParam pp)
        {
            return null;
        }

        #region 是否存在

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(int id)
        {
            return MyDAL.GetInfo(id) != null;
        }

        #endregion

        #region 为会员显示内容

        /// <summary>
        /// 为会员显示内容
        /// </summary>
        /// <param name="modelId"></param>
        /// <param name="contentId"></param>
        /// <param name="pageNo"></param>
        public Result ShowContent(byte modelId, int contentId, int pageNo)
        {
            Result res = new Result();
            if (RightsCheck.IsLogined == false)
            {
                res.Errors = "该文章为会员文章，请先登录。<br />登录后可能需要刷新。";
                return res;
            }

            User user = new UserManage().GetInfo(UserManage.Current.UserID);

            if (UserManage.Current.ActiveType == 2)
            {
                if (user.Mature < DateTime.Today)
                {
                    res.Errors = "对不起，你的会员期已经过了。";
                    return res;
                }
            }

            dynamic content = new CoreManage().GetBaseInfo(modelId, contentId);

            int intPoint = user.Point;
            int intCoin = user.Coin;
            int intArticlePoint = Convert.ToInt32(content.PointNum);
            if (intPoint < intArticlePoint)
            {
                if (intCoin > 0)
                {
                    CMSConfig config = CMSConfig.Instance();
                    res.Errors = "对不起，你的点数不够，但你还有" + intCoin + "个" + config.Member.JingBiMingCheng + "请把它转化为点数。";
                    return res;
                }
                res.Errors = "对不起，你的点数不够。";
                return res;
            }

            //如果权限足够
            if (content.Rank <= UserManage.Current.Rank)
            {
                string strContent = content.Content;
                if (strContent.Contains("@Next@"))
                {
                    string[] strArr = Regex.Split(strContent, "@Next@", RegexOptions.IgnoreCase);

                    res.Data = strArr[pageNo - 1]; //当前页的文章内容
                    return res;
                }
                CMSConfig config = CMSConfig.Instance();
                if (config.Article.AutoCutPage)
                {
                    string[] strArr = Regex.Split(strContent, @"<br\s*?/*?>", RegexOptions.IgnoreCase);

                    StringBuilder sbContent = new StringBuilder();
                    int temp = ((pageNo - 1) * PageFactory.Pages.ArticleCommon.BrNum);
                    int maxIndex = temp + PageFactory.Pages.ArticleCommon.BrNum;
                    if (maxIndex > strArr.Length)
                    {
                        maxIndex = strArr.Length;
                    }
                    for (int I = temp; I < maxIndex; I++)
                    {
                        sbContent.Append(strArr[I] + "<br>");
                    }

                    res.Data = sbContent.ToString(); //当前页的文章内容
                }
                else
                {
                    res.Data = strContent;
                }

                //如果不是包月
                if (UserManage.Current.ActiveType != 2 && pageNo == 1)
                {
                    #region 如果没有免费看文章的待遇

                    if (RightsCheck.HasRight("Member_1") == false)
                    {
                        //如果没有读过
                        BusinessManage myBusinessCategory = new BusinessManage();
                        DateTime? businessReaded = myBusinessCategory.CheckReaded(contentId, UserManage.Current.UserID);

                        Business model = new Business
                        {
                            Flag = 1,
                            CreateTime = DateTime.Now,
                            Customer = UserManage.Current.UserName,
                            Point = content.PointNum,
                            PayMoney = 0,
                            Indent = contentId,
                            UserId = UserManage.Current.UserID,
                            Remark = "使用收费内容，扣点数。"
                        };

                        if (businessReaded == null)
                        {
                            new MemberManage().KouDianShu(content.PointNum, UserManage.Current.UserID);
                            new BusinessManage().Add(model);
                        }
                        else
                        {
                            double dec = MyDateTime.DateDiff(DateDiffOption.Day, (DateTime)businessReaded, DateTime.Now);
                            if (dec > 0)
                            {
                                new MemberManage().KouDianShu(content.PointNum, UserManage.Current.UserID);
                                new BusinessManage().Add(model);
                            }
                        }
                    }

                    #endregion
                }

                return res;
            }
            res.Errors = "对不起，你的等级不够。";
            return res;
        }

        #endregion

        #region 批量执行一些操作

        /// <summary>
        /// 批量执行一些操作
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="which"></param>
        [Logging, ExceptionCall]
        public Result BatchToDo(string ids, BatchToDo which)
        {
            Result resu = new Result();
            if (ids == null && which != Model.Enum.BatchToDo.审核所有)
            {
                resu.Errors = "请选中一条记录";
                return resu;
            }


            if (string.IsNullOrEmpty(ids)) //如果是“全部审核”则随便传递一个值
            {
                ids = "0";
            }

            var contentids = ids.ToArrInt();
            MyDAL.BatchToDo(contentids, which);

            if (ids != "0")
            {
                foreach (var id in contentids)
                {
                    DeleteHTML.ContentPage(id);

                    MakeSinglePage.ContentPageHTML(id);
                }
            }

            resu.LogMessage = which + "记录 " + ids;

            return resu;
        }

        #endregion

        #region 具有幻灯片属性的内容

        /// <summary>
        /// 具有幻灯片属性的内容
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public IEnumerable<Core> SlideContents(int topNo, int parentId)
        {
            IEnumerable<int> categoryIds = CategoryManage.GetDescendantIds(parentId);
            var list = MyDAL.SlideContents(topNo, categoryIds);
            foreach (Core t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }
            return list;
        }

        #endregion

        #region 最新内容

        /// <summary>
        /// 取得栏目下的最新内容
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public IEnumerable<Core> Latests(int topNo, int categoryId)
        {
            var list = MyDAL.Latests(categoryId, topNo);


            foreach (Core t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }
            return list;
        }

        #endregion

        #region 相关内容

        /// <summary>
        /// 相关内容
        /// </summary>
        /// <param name="top"></param>
        /// <param name="id"></param>
        /// <param name="tags"></param>
        /// <returns></returns>
        public IEnumerable<Core> RelatedContents(int top, int id, string tags)
        {
            var list = MyDAL.RelatedContent(top, id, tags);
            foreach (Core t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }
            return list;
        }

        #endregion

        #region 上篇，下篇

        /// <summary>
        /// 上篇，下篇
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Core[] PreNextContents(int id)
        {
            IList<Core> list = MyDAL.PreNextContents(id);
            for (var i = 0; i < list.Count; i++)
            {
                if (list[i] != null)
                    list[i].Link = StaticFilePath.ContentShowUrl(list[i]);
                else
                {
                    list[i] = new Core();
                    list[i].Link = "#";
                }
            }
            Core[] infos = new Core[2];

            infos[0] = list.FirstOrDefault(x => x.Brief == "上一页");
            infos[1] = list.FirstOrDefault(x => x.Brief == "下一页");
            return infos;
        }

        #endregion

        #region 查询内容

        /// <summary>
        /// 查询内容
        /// </summary>
        /// <param name="sort"></param>
        /// <param name="keyword"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Core> Search(string sort, string keyword, PagingParam pp)
        {
            string[] keywords;
            if (string.IsNullOrWhiteSpace(keyword))
            {
                keywords = new string[0];
            }
            else
            {
                keywords = keyword.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            }
            IList<Core> list = MyDAL.Search(sort, keywords, pp);
            foreach (Core t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }
            return list;
        }

        #endregion

        #region 增加阅读量

        /// <summary>
        /// 增加阅读量
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pageNo"></param>
        public int UpDateHits(int id, int pageNo)
        {
            int hits;
            if (pageNo <= 1)
            {
                hits = MyDAL.UpDateHits(id, true);
            }
            else
            {
                hits = MyDAL.UpDateHits(id, false);
            }
            return hits;
        }

        #endregion

        #region 绑定简单内容

        /// <summary>
        /// 绑定简单内容
        /// </summary>
        /// <param name="model"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IEnumerable<IContent> BindList(Model.Model model, PagingParam pp)
        {
            switch (model.BaseModel)
            {
                case "Soft":
                    return new SoftDal().BindList(pp);
                case "Article":
                    return new ArticleDal().BindList(pp);
                case "Photo":
                    return new PhotoDal().BindList(pp);
                case "Shop":
                    return new GoodsDal().BindList(pp);
                default:
                    throw new NotSupportedException("参数错误。");
            }
        }

        /// <summary>
        /// 绑定简单内容
        /// </summary>
        /// <returns></returns>
        public int Count(Model.Model model)
        {
            switch (model.BaseModel)
            {
                case "Soft":
                    return new SoftDal().Count();
                case "Article":
                    return new ArticleDal().Count();
                case "Photo":
                    return new PhotoDal().Count();
                case "Shop":
                    return new GoodsDal().Count();
                default:
                    throw new NotSupportedException("参数错误。");
            }
        }

        #endregion

        /// <summary>
        /// 批量移动文章到某栏目
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="categoryId"></param>
        /// <param name="updatePanel1"></param>
        public void MoveToNewCategory(string ids, string categoryId, UpdatePanel updatePanel1)
        {
            if (Convert.ToInt32(categoryId) > 0)
            {
                MyDAL.MoveToNewCategory(ids, int.Parse(categoryId));

                Log logModel = new Log { Type = "内容管理", Event = "移动" + ids + "到栏目ID：" + categoryId };
                LogManage.Add(logModel);

                MsgBox.Message("操作成功！", updatePanel1);
            }
            else
            {
                MsgBox.Message("你没有选择栏目！", updatePanel1);
            }
        }

        #region 批量修改属性

        /// <summary>
        /// 批量修改属性
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="ids"></param>
        public Result BatchUpData(dynamic datas, string ids)
        {
            Result res = new Result();
            if (ids.Length == 0)
            {
                res.Errors = "请选择要执行的内容";
                return res;
            }
            bool err = true;
            foreach (var b in datas)
            {
                if (true == b.Checked)
                {
                    err = false;
                    break;
                }
            }

            if (err)
            {
                res.Errors = "至少要选择一个！";
                return res;
            }


            Log logModel = new Log();
            logModel.Type = "内容管理";
            logModel.Event = "批量修改属性 ,ID:" + ids;
            LogManage.Add(logModel);

            MyDAL.BatchUpData(datas, ids);

            return res;
        }

        #endregion

        #region 批量移动问答到某专题

        /// <summary>
        /// 批量移动问答到某专题
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="specialId"></param>
        /// <param name="UpdatePanel1"></param>
        public void MoveToNewSpecial(string ids, string specialId, UpdatePanel UpdatePanel1)
        {
            MyDAL.MoveToNewSpecial(ids, int.Parse(specialId));

            Log logModel = new Log();
            logModel.Type = "内容管理";
            if (specialId == "0")
            {
                logModel.Event = "取消" + ids + "的专题属性";
            }
            else
            {
                logModel.Event = "移动" + ids + "到专题ID：" + specialId;
            }
            LogManage.Add(logModel);

            MsgBox.Message("操作成功！", UpdatePanel1);
        }

        #endregion

        #region 回收站

        /// <summary>
        /// 回收站
        /// </summary>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Core> RecyclebinList(PagingParam pp)
        {
            return MyDAL.RecyclebinList(pp);
        }

        #endregion

        #region 删除或者还原

        /// <summary>
        /// 删除或者还原
        /// 0 逻辑删除;1 物理删除;2 还原所有;3 还原选中 ;4 清空回收站
        /// </summary>
        /// <param name="IDs"></param>
        /// <param name="Type"></param>
        public void DeleteAndUndelete(string IDs, int Type, UpdatePanel UpdatePanel1)
        {
            if (string.IsNullOrEmpty(IDs))
            {
                MsgBox.Message("请选择一个删除的目标！", UpdatePanel1);
                return;
            }

            int[] ids = MyDAL.DeleteAndUndelete(IDs, Type);

            foreach (var id in ids)
            {
                DeleteHTML.ContentPage(id);
                MakeSinglePage.ContentPageHTML(id);
            }

            Log logModel = new Log();
            logModel.Type = "内容管理";

            switch (Type)
            {
                case 0:
                    logModel.Event = "逻辑删除" + IDs;
                    break;
                case 1:
                    logModel.Event = "物理删除" + IDs;

                    break;
                case 2:
                    logModel.Event = "还原所有" + IDs;
                    break;
                case 3:
                    logModel.Event = "还原选中" + IDs;
                    break;
                case 4:
                    logModel.Event = "清空回收站";
                    break;
            }

            LogManage.Add(logModel);
        }

        #endregion

        #region 前台通用绑定

        /// <summary>
        /// 前台通用绑定
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="keyword"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Core> CategoryPageBindList(int categoryId, string keyword, PagingParam pp)
        {
            var categoryIds = CategoryManage.GetDescendantIds(categoryId);

            IList<Core> list = MyDAL.CategoryPageBindList(categoryIds, pp);

            list.ForEach(x => x.Link = StaticFilePath.ContentShowUrl(x));

            return list;
        }

        #endregion

        #region 图文列表

        /// <summary>
        /// 图文列表
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public IEnumerable<Core> PicContents(int topNo, int parentId)
        {
            IEnumerable<int> categoryIds = CategoryManage.GetDescendantIds(parentId);
            var list = MyDAL.PicContents(topNo, categoryIds);
            foreach (var t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }
            return list;
        }

        #endregion

        #region 热门内容

        /// <summary>
        /// 热门内容
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="categoryId"></param>
        /// <param name="timeSpan">时间范围</param>
        /// <returns></returns>
        public IList<Core> HotContents(int topNo, int categoryId, string timeSpan)
        {
            //var ids = CategoryManage.GetDescendantIDs(CategoryId);

            DateTime DTs;
            DateTime DTe;
            if (timeSpan == "Week")
            {
                DayOfWeek dow = DateTime.Today.DayOfWeek;
                DTs = DateTime.Today.AddDays(-(int)dow);
                DTe = DateTime.Today.AddDays(7 - (int)dow).AddSeconds(-1);
            }
            else
            {
                DateTime dt = DateTime.Today;
                DTs = Convert.ToDateTime(dt.ToString("yyyy-MM-01"));
                DTe = DTs.AddMonths(1).AddSeconds(-1);
            }

            var list = MyDAL.HotContents(topNo, categoryId, DTs, DTe, timeSpan);

            foreach (Core t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }
            return list;
        }

        #endregion

        #region 推荐内容

        /// <summary>
        /// 推荐内容
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public IEnumerable<Core> EliteContents(int topNo, int parentId)
        {
            var ids = CategoryManage.GetDescendantIds(parentId);
            var list = MyDAL.EliteContents(topNo, ids);
            foreach (Core t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }
            return list;
        }

        #endregion

        #region 头条内容

        /// <summary>
        /// 头条内容
        /// </summary>
        /// <param name="topNo">提取N条</param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public IEnumerable<Core> HeadlineContents(int topNo, int parentId)
        {
            var list = MyDAL.HeadlineContents(topNo, parentId);
            foreach (Core t in list)
            {
                t.Link = StaticFilePath.ContentShowUrl(t);
            }
            return list;
        }

        #endregion

        #region 更新评论信息

        /// <summary>
        /// 更新评论信息
        /// </summary>
        /// <param name="contentId"></param>
        public void UpdateCommentInfo(int contentId)
        {
            MyDAL.UpdateCommentInfo(contentId);
        }

        #endregion

        #region 绑定数据

        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Core> BindList(HttpContext context, PagingParam pp)
        {
            string FieldSort = context.Request["FieldSort"];
            string KeyWord = context.Request["KeyWord"];
            byte ModelId = byte.Parse(context.Request["ModelId"]);
            string CategoryId = context.Request["CategoryId"];
            bool IsEditor = bool.Parse(context.Request["IsEditor"]);
            bool IsSpecial = bool.Parse(context.Request["IsSpecial"]);
            bool IsOnTop = bool.Parse(context.Request["IsOnTop"]);
            bool IsElite = bool.Parse(context.Request["IsElite"]);
            bool IsChecked = bool.Parse(context.Request["IsChecked"]);
            bool IsUnChecked = bool.Parse(context.Request["IsUnChecked"]);
            bool IsDraft = bool.Parse(context.Request["IsDraft"]);
            bool IsSlide = bool.Parse(context.Request["IsSlide"]);


            bool? IsUnClose = null;
            if (context.Request["IsUnClose"] != null)
                IsUnClose = bool.Parse(context.Request["IsUnClose"]); //问答模型"未解决"属性


            pp.PageNo = int.Parse(context.Request["page"]);
            pp.PageSize = int.Parse(context.Request["rows"]);
            pp.RecordCount = Convert.ToInt32(context.Request["recordCount"]);

            string where = " IsDeleted=false";

            #region 构建查询条件

            if (string.IsNullOrWhiteSpace(KeyWord) == false)
            {
                KeyWord = MyString.SQL_ESC(KeyWord);

                where += " AND " + FieldSort + " like '%" + KeyWord + "%'";
            }
            if (ModelId > 0 && string.IsNullOrEmpty(CategoryId))
            {
                var ids = CategoryManage.GetDescendantIDsByModelId(ModelId);
                where += @" AND (" + string.Join(" OR ", ids.Select(x => "CategoryId=" + x)) + ")";
            }
            else if (string.IsNullOrEmpty(CategoryId) == false)
            {
                var ids = CategoryManage.GetDescendantIds(CategoryId.ToInt());
                where += @" AND (" + string.Join(" OR ", ids.Select(x => "CategoryId=" + x)) + ")";
            }
            if (IsEditor)
            {
                where += " AND Editor='" + UserManage.Current.UserName + "'";
            }
            if (IsSpecial)
            {
                where += " AND SpecialID>0";
            }

            if (IsOnTop)
            {
                where += " AND IsOnTop=true";
            }
            if (IsElite)
            {
                where += " AND IsElite=true";
            }
            if (IsUnChecked != IsChecked)
            {
                if (IsChecked)
                {
                    where += " AND IsChecked=true";
                }
                if (IsUnChecked)
                {
                    where += " AND IsChecked=false";
                }
            }
            //if (IsDraft)
            //{
            //    Where += " AND IsDraft=true";
            //} 
            if (IsSlide)
            {
                where += " AND IsSlide=true";
            }
            if (IsUnClose != null)
            {
                where += " AND State=false";
            }

            #endregion

            var list = MyDAL.BindList(context.Request["sort"], context.Request["Order"], where, pp);
            list.ForEach(x => x.ContentTitle = Common.Security.Encoder.HtmlEncode(x.ContentTitle));
            return list;
        }

        #endregion
    }
}